	import {pathToBase64} from '@/Mixins/index.js'	
export const mixin = {
	data(){
		return{
			isWxH5:false,
			wxLoading:false,
			toUrl:'',
			toData:{},
			isTo:true,
			imgInfo:''
		}
	},
	mounted(){
		// this.getCode()
		
	},
	methods:{
		
		toPage(url,data={}){
			
			this.toUrl = url
			this.toData = data
			// console.log('[路由跳转]',this.toUrl,this.toData)
			if(this.isTo){
				this.isTo = false
				this._toPage()
			}
			// uni.$u.throttle(,500,true)
		},
		_toPage(){
			// console.log('[路由跳转]',this.toUrl,this.toData)
			uni.$u.route({
				url: this.toUrl,
				params: this.toData
			})
			uni.$u.route({
				type:'switchTab',
				url: this.toUrl,
				params: this.toData
			})
			setTimeout(()=>{
				this.isTo = true
			},1000)
		},
		//资讯信息
		async articleList(type,page=1,size=10,search=''){
			let params = {
				page:page,
				page_size:size,
				type:type
			}
			if(search){
				params.search = search
			}
			let data = await this.$http({
				url:this.$api.articleList,
				method: 'GET',
				hideLoading: true,
				data: params
			})
			// console.log('[资讯信息]',data)
			if(data.code==200){
				return new Promise((resolve, reject) => {
					resolve( {
					code:data.code,
					total:data.data.total,
					data:data.data.data,
					})
				})
			}else{
				return new Promise((resolve, reject) => {
					resolve([])
				})
			}
		},
		//资讯详情
		async articleRead(id){
			let data = await this.$http({
				url:this.$api.articleRead,
				method: 'GET',
				hideLoading: true,
				data:{
					id:id
				}
			})
			// console.log('[资讯详情]',data)
			if(data.code==200){
				return {
					code:data.code,
					data:data.data,
				}
			}else{
				return []
			}
		},
		//说明
		async getConfigDetail(name){
			let data = await this.$http({
				url:this.$api.getConfigDetail,
				method: 'GET',
				hideLoading: true,
				data:{
					name:name
				}
			})
			//console.log('[说明]',data)
			if(data.code==200){
				let res = data.data.find(item=>{
					return item.name == name
				})
				return {
					code:data.code,
					data:res,
				}
			}else{
				return {}
			}
		},
		//下载资源
		downloadFile(url){
			// #ifdef MP-WEIXIN
			uni.downloadFile({
			    url: url,
			    success: (res) => {
					// console.log('[下载成功]',res);
					uni.showLoading({
					    title: '正在保存图片'
					});
			        if (res.statusCode === 200) {
						
						uni.saveImageToPhotosAlbum({
						    filePath: res.tempFilePath,
						    success:()=> {
						        uni.showToast({
						            title: '图片已成功保存到相册',
									icon:'none',
						            duration: 2000
						        });
						    },
							fail: (err) => {
								// console.log('[保存失败]',err)
								uni.hideLoading()
								uni.getSetting({
									success:(res)=> {
										if(!res.authSetting['scope.writePhotosAlbum']){
											uni.showModal({
											    title: '提示',
												icon:'none',
											    content: '未获取到相关权限，是否授权',
											    success:(res)=> {
											        if (res.confirm) {
											            uni.openSetting({
															success:(res)=> {
																// console.log(res.authSetting,url)
																if(res.authSetting['scope.writePhotosAlbum']){
																	this.downloadFile(url)
																}else{
																	uni.showToast({
																	    title: '暂无权限-保存失败',
																		icon:'none',
																	    duration: 2000
																	});
																}
															}
											            });
											        } else if (res.cancel) {
											            uni.showToast({
											                title: '暂无权限-保存失败',
															icon:'none',
											                duration: 2000
											            });
											        }
											    }
											});
										}
									}
								})
							}
						});
						
			        }
			    },
				fail: (err) => {
					// console.log('[下载失败]',err)
					uni.showToast({
					    title: '图片保存失败',
						icon:'none',
					    duration: 2000
					});
				}
			});
			// #endif
		},
		
		// H5支付
		async topay(id,type) {
			if(type=='money'){
				uni.redirectTo({
					url:'/subpage/webview/webview?orderSn='+id
				});
			}else{
			uni.redirectTo({
				url:'/subpage/webview/webview?webid='+id
			});
			}
			
			
			// let url = 'https://pay.zyrnft.com/v1/paySDOrder?id=' + id
			// this.loading = false
			// //#ifdef H5
			// window.open(url)
			// //#endif
			// // #ifdef APP
			// plus.runtime.openURL(url)
			// // #endif
		},
		
		async shayuSms(e){
			uni.showLoading({
			  title: '正在获取验证码'
			})
			let data = await this.$http({
				url:this.$api.shayuSms,
				method: 'POST',
				hideLoading: true,
				data:{
					username : e||this.form.username
				}
			})
			// console.log('[获取验证码]',data)
			this.loading = false
			if(data.code==200){
				uni.hideLoading();
				// 这里此提示会被this.start()方法中的提示覆盖
				uni.$u.toast('验证码已发送');
				// 通知验证码组件内部开始倒计时
				this.$refs.uCode.start();
			}else{
				uni.showToast({
				    title: data.msg||'重置密码失败',
					icon:'none',
				    duration: 2000
				})
			}
		},
		async setMemberInfo(e){
			let data = await this.$http({
				url:this.$api.setMemberInfo,
				method: 'POST',
				hideLoading: true,
				data:e
			})
			this.loading = false
			uni.showToast({
			    title: data.msg||'修改失败',
				icon:'none',
			    duration: 2000
			})
			// if(data.code==201){
			// 	setTimeout(()=>{
			// 		uni.navigateBack({
			// 			delta:1,
			// 			fail:(err)=>{
			// 				// console.log('[返回登录前失败]',err)
			// 				uni.switchTab({
			// 					url: '/pages/Index/index'
			// 				});
			// 			}
			// 		});
			// 	},1500)
			// }
		},
		//公众号登录-获取code
		async getWxCode() {
			// 授权回调
			let local = 'https://pro.jrxtiejin.com/index.html#'+this.$route.path;
			let url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxe536bf668525e37a&redirect_uri=" +
				encodeURIComponent(local) +"&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
			let code = this.GetParam(window.location.href.split("#")[0], "code");
			// console.log('[CODE]',code)
			if (!code) {
				window.location.href = url;
			} else {
				let code = this.GetParam(window.location.href, "code");
				this.GetUserInfo(code)
				// console.log("code", code);
			}
		},
		//公众号登录-获取用户信息
		async GetUserInfo(code){
			let data = await this.$http({
				url:this.$api.GetUserInfo,
				method: 'GET',
				hideLoading: true,
				data:{
					code:code
				}
			})
			// console.log('[获取用户信息]',data)
			this.wxLoading = false
			if(data.code==200){
				let res = data.data
				if(res.token){
					this.$store.commit('ChangeUserInfo',res.member);
					this.$store.commit('ChangeToken',res.token);
					this.back()
				}else{
					this.$store.commit('ChangeUserInfo',res.user_info);
				}
			}else{
				uni.showToast({
					title: '用户信息获取失败-登录失败',
					duration: 2000,
					icon:'none'
				});
				this.$store.commit('ChangeUserInfo',{});
				this.$store.commit('ChangeToken','');
				setTimeout(()=>{
					this.back()
				},1500)
			}
		},
		async WxLogin(){
			let data = await this.$http({
				url:this.$api.WxLogin,
				method: 'POST',
				hideLoading: true,
				data:{
					wxopenid :this.userInfo.openid,
					nickName :this.userInfo.nickname,
					mobile:this.form.username,
					avatarUrl : this.userInfo.headimgurl,
					gender :this.userInfo.sex,
					verify_code : this.form.verify_code,
					unionid : this.userInfo.unionid
				}
			})
			// console.log('[公众号绑定用户信息]',data)
			if(data.code==200){
				let res = data.data
				this.$store.commit('ChangeUserInfo',res.member);
				this.$store.commit('ChangeToken',res.token);
				this.back()
			}else{
				uni.showToast({
				    title: data.msg||'登录失败',
					icon:'none',
				    duration: 2000
				})
			}
		},
		// 截取code
		GetParam(url, code) {
			url = url + "";
			let regstr = "/(\\?|\\&)" + code + "=([^\\&]+)/";
			let reg = eval(regstr);
			//eval可以将 regstr字符串转换为 正则表达式
			let result = url.match(reg);
			if (result && result[2]) {
				return result[2];
			}
		},
		//判断是否为微信浏览器内
		toweichat() {
		    //判断是否是微信浏览器
			var ua = navigator.userAgent.toLowerCase();  
			if(ua.match(/MicroMessenger/i)=="micromessenger") {  
			    this.isWxH5 = true
				this.wxLoading = true
			    this.rules.verify_code[0].required = true
			    this.rules.password[0].required = false
			    this.getWxCode()
			} else {  
			    return false;  
			}
		     
		},
		imagesBase(obg,path,name){			
			uni.request({
			 url: path,
			 method: 'GET',
			 responseType: 'arraybuffer',
			 success:  res => {
			   let base64 = uni.arrayBufferToBase64(res.data); //把arraybuffer转成base64
			  let toBase64Url = 'data:image/jpeg;base64,' + base64; //不加上这串字符，在页面无法显示
				this.$set(obg,name,toBase64Url)	
			  }
			 });
			 
			// pathToBase64(path)
			//   .then(base64 => {
			//     this.$set(obg,name,base64)
			// 	console.log(1);
			//   })
			//   .catch(error => {
			//     console.error(error)
			//   })
		},
		back(){
			// console.log('[准备路由跳转]')
			let routes = getCurrentPages();
			// console.log('[路由跳转]',routes)
			if(routes.length>1&&(routes[routes.length-1]!=routes[routes.length-2])){
				uni.navigateBack({
					delta:1,
					success:(e)=>{
						// console.log('[返回成功]',e)
					},
					fail:(err)=>{
						// console.log('[返回登录前失败]',err)
						uni.switchTab({
							url: '/pages/Index/index'
						});
					}
				});
			}else{
				uni.switchTab({
					url: '/pages/Index/index'
				});
			}
			
		},
		imageLoad(list,path,i,name) {
			pathToBase64(path)
			  .then(base64 => {
			    this.$set(list[i],name,base64)
			  })
			  .catch(error => {
			    console.error(error)
			  })
		},
			recursion(imgInfo,callback){
						const ctx = uni.createCanvasContext('myCanvas', this);
						let i = Math.floor(340 /( imgInfo.width / imgInfo.height));
						let imgHeight = 340
						if(imgInfo.width==imgInfo.height){
							imgHeight = 340
						}else{
							imgHeight = i
						}
						ctx.drawImage(imgInfo.path, 0, 0, 340, imgHeight);
						ctx.draw(false, () => {
							// canvas画布转成图片并返回图片地址
							uni.canvasToTempFilePath({
									canvasId: 'myCanvas',
									x:0,
									y:0,
									width: 340,
									height: imgHeight,
									destWidth: 340*0.8,
									destHeight: imgHeight*0.8,
									success: res => {
										// console.log('[res]',res)
										// #ifdef H5
										callback(res.tempFilePath);
										// #endif
										// #ifdef APP
										pathToBase64(res.tempFilePath)
										  .then(base64 => {
											   // console.log('base64------',base64)
										    // this.$set(list[i],name,base64)
											callback(base64);
										  })
										  .catch(error => {
											  // console.log(error);
										  })
										// #endif
										
									},
									fail: err => {
										
									}
								}
							);
						});
					},
		// 压缩图片的方法
		       canvasDataURL(path, obj, callback){
		          var img = new Image();
		          img.src = path;
		          img.setAttribute("crossOrigin",'Anonymous')
		          img.onload = function(){
		              var that = this;
		              // 默认按比例压缩
		              var w = that.width,
		                  h = that.height,
		                  scale = w / h;
		              w = obj.width || w;
		              h = obj.height || (w / scale);
		              var quality = 0.7;  // 默认图片质量为0.7
		              //生成canvas
		              var canvas = document.createElement('canvas');
		              var ctx = canvas.getContext('2d');
		              // 创建属性节点
		              var anw = document.createAttribute("width");
		              anw.nodeValue = w;
		              var anh = document.createAttribute("height");
		              anh.nodeValue = h;
		              canvas.setAttributeNode(anw);
		              canvas.setAttributeNode(anh);
		              ctx.drawImage(that, 0, 0, w, h);
		              // 图像质量
		              if(obj.quality && obj.quality <= 1 && obj.quality > 0){
		                  quality = obj.quality;
		              }
		              // quality值越小，所绘制出的图像越模糊
		              var base64 = canvas.toDataURL('image/jpeg', quality);
		              // 回调函数返回base64的值
					  // console.log('1------------------------------');
		              callback(base64);
		          }
		      }
		
		
		
	}
}